package cn.rentaotao.spring.web;

import cn.rentaotao.spring.data.Spittle;
import cn.rentaotao.spring.exception.SpittleException;
import cn.rentaotao.spring.service.SpittleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Part;
import java.util.List;

/**
 * @author rtt
 * @date 2022/5/11 15:58
 */
@Controller
@RequestMapping("/spittle")
@Conditional(SpittleCondition.class)
public class SpittleController {

    private final SpittleService spittleService;

    @Autowired(required = false)
    public SpittleController(SpittleService spittleService) {
        this.spittleService = spittleService;
    }

    @RequestMapping(path = "/jsp/get", method = RequestMethod.GET)
    public String showRecentSpittles(@RequestParam(value = "start", defaultValue = "0") int start,
                                     @RequestParam(value = "count", defaultValue = "10") int count,
                                     Model model) throws SpittleException {

        model.addAttribute("spittleList", spittleService.getSpittleList(start, count));

        return "spittles";
    }

    /**
     * {@link ResponseEntity} 相当与指定 http code，返回 ResponseBody
     *
     * @param start 开始序号
     * @param count 数量
     * @return ResponseEntity
     */
    @RequestMapping(path = "/entity/get/{start}/{count}")
    public ResponseEntity<List<Spittle>> getSpittleList(@PathVariable("start") int start, @PathVariable("count") int count) {

        List<Spittle> spittleList = spittleService.getSpittleList(start, count);

        return new ResponseEntity<>(spittleList, HttpStatus.OK);
    }

    /**
     * 通过 @RequestPart 可以获得 multipart/form-data 请求的某项属性
     *
     * @param file 二进制文件
     * @return 视图名称
     */
    @RequestMapping(value = "/multipart", method = RequestMethod.POST)
    public String processMultipart(@RequestPart("file") byte[] file) {

        return "";
    }

    @RequestMapping(value = "/multipart1", method = RequestMethod.POST)
    public String processMultipart1(MultipartFile file) {

        return "";
    }

    /**
     * servlet3.0 以上适用
     * 通过这种方式就没必要配置 MultipartResolver
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/multipart2", method = RequestMethod.POST)
    public String processMultipart2(Part file) {

        return "";
    }

    /**
     * 能够处理同一个控制器中的其他处理器的异常
     *
     * @return 返回异常信息
     */
    @ExceptionHandler(SpittleException.class)
    @ResponseBody
    public String handleException() {

        return "程序异常";
    }
}
